package com.wsdk.util;

import android.content.Context;
import android.content.SharedPreferences;

import com.wsdk.Wsdk;

import java.util.ArrayList;
import java.util.List;

/**
 * @author fionera
 */
public class SPUtil {
    protected static SharedPreferences mSharedPreferences;

    private static void init() {
        LogUtil.d("Original SPUtil");
        if (mSharedPreferences == null && Wsdk.getInstance() != null) {
            mSharedPreferences = Wsdk.getInstance().getSharedPreferences("wsdk_prefs", Context.MODE_PRIVATE);
        }
        LogUtil.d(mSharedPreferences + "");
    }

    static {
        init();
    }

    private static void setInt(String key, int value) {
        mSharedPreferences.edit().putInt(key, value).apply();
    }

    private static int getInt(String key) {
        return mSharedPreferences.getInt(key, 0);
    }


    public static void setBoolean(String key, boolean value) {
        mSharedPreferences.edit().putBoolean(key, value).apply();
    }

    public static boolean getBoolean(String key) {
        return getBoolean(key, false);
    }

    public static boolean getBoolean(String key, boolean defaultValue) {
        return mSharedPreferences.getBoolean(key, defaultValue);
    }

    public static void setString(String key, String value) {
        mSharedPreferences.edit().putString(key, value).apply();
    }

    public static String getString(String key) {
        return getString(key, "");
    }

    public static String getString(String key, String defaultValue) {
        return mSharedPreferences.getString(key, defaultValue);
    }

    public static void remove(String key) {
        mSharedPreferences.edit().remove(key).apply();
    }

    public static void clearAll() {
        mSharedPreferences.edit().clear().apply();
    }

    public static void putStrListValue(Context context, String key,
                                       List<String> strList) {
        if (null == strList) {
            return;
        }
        // 保存之前先清理已经存在的数据，保证数据的唯一性
        removeStrList(context, key);
        int size = strList.size();
        setInt(key + "size", size);
        for (int i = 0; i < size; i++) {
            setString(key + i, strList.get(i));
        }
    }
    private static void removeStrList(Context context, String key) {
        int size = getInt(key + "size");
        if (0 == size) {
            return;
        }
        remove(key + "size");
        for (int i = 0; i < size; i++) {
            remove(key + i);
        }
    }
    public static List<String> getStrListValue(Context context, String key) {
        List<String> strList = new ArrayList<>();
        int size = getInt(key + "size");
        for (int i = 0; i < size; i++) {
            strList.add(getString( key + i, null));
        }
        return strList;
    }
}
